package utils

import (
	"log"

	"net/http"

	"encoding/xml"

	"encoding/json"

	"bytes"

	"encoding/base64"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/gorilla/websocket"
)

func (socketdata *WEBSOCKET_DATA) WriteData(c *websocket.Conn) {
	if err := c.WriteJSON(socketdata); err != nil {
		log.Println("#write json error:", err.Error())
	}
}

func (socketerror *WEBSOCKET_ERR) WriteError(c *websocket.Conn) {
	if err := c.WriteJSON(socketerror); err != nil {
		log.Println("#write json error:", err.Error())
	}
}

func WriteError(format string, status int, description string, w http.ResponseWriter) {
	errinfo := ERROR_XML{xml.Name{}, status, description}
	var str []byte
	var err error

	switch format {
	case ".json":
		if str, err = json.Marshal(map[string]ERROR_XML{"error": errinfo}); err != nil {
			log.Println("#WriteXmlError:", err.Error())
		}

		var out bytes.Buffer

		json.Indent(&out, str, "", "  ")

		io.WriteString(w, out.String())
	case ".xml":
		fallthrough
	default:
		if str, err = xml.Marshal(errinfo); err != nil {
			log.Println("#WriteXmlError:", err.Error())
		}

		io.WriteString(w, xml.Header)
		io.WriteString(w, string(str))
	}
}

func WriteWsError(action string, status int, description string, c *websocket.Conn) {
	data := WEBSOCKET_ERR{
		action,
		ERROR_XML{xml.Name{}, status, description},
	}

	data.WriteError(c)
}
func WriteWsData(action string, data interface{}, c *websocket.Conn) {
	w := WEBSOCKET_DATA{
		action,
		data,
	}

	w.WriteData(c)
}

func WriteEmpty(format string, w http.ResponseWriter) {
	type ok struct{}
	WriteData(format, ok{}, w)
}
func WriteData(format string, data interface{}, w http.ResponseWriter) {
	var str []byte
	var err error

	switch format {
	case ".json":
		str, _ = json.Marshal(data)
		var out bytes.Buffer

		json.Indent(&out, str, "", "  ")

		str = out.Bytes()

	case ".xml":
		fallthrough
	default:
		io.WriteString(w, xml.Header)
		if str, err = xml.Marshal(data); err != nil {
			log.Println("#write data error:", err.Error())
		}
	}

	io.WriteString(w, string(str))
}

func ToImageFile(id, b64 string) (string, error) {
	var buf []byte
	var err error
	url := AppPath() + "/html/data/image/" + id + ".png"
	if err = os.MkdirAll(filepath.Dir(url), os.ModePerm); err != nil {
		return "", err
	}

	if buf, err = base64.StdEncoding.DecodeString(b64); err != nil {
		return "", err
	}

	if err = ioutil.WriteFile(url, buf, 0666); err != nil {
		return "", err
	}
	if url, err = filepath.Rel(AppPath()+"/html", url); err != nil {
		return "", err
	}

	return filepath.ToSlash("/" + url), nil
}
